<template>
  <div class="body_bgi full relative pt_15 scroll_box overflow_y_auto">
    <!-- 分组列表 -->
    <div class="w_full h_40 lh_40 flex_row_start ph_10">
      <div 
        class="w_25_p text_center ph_10 color_fff fs_1rem relative" 
        :class="{ 'main_color': groupId == group.id }"
        v-for="(group, index) in groupList" :key="index"
        @click="clickGroup(group)">
        {{ group.name }}
        <div class="bottom_border" v-show="groupId == group.id"></div>
      </div>
    </div>

    <!-- 选手列表 -->
    <div 
      ref="scroll_box" 
      class="list_box w_full mt_20 flex_row_start x_scroll overflow_x_auto"
      :class="screenWidth < 600 ? 'h_20_p' : 'h_18_p'"
    >
      <div 
        :id="index"
        :style="{width: personItemWidth + 'px'}"
        class="h_full flex_shrink_0 ph_5" 
        v-for="(item, index) in personList" :key="index"
        ref="personItem"
        @click="clickPersonItem(index)"
      >
        <div 
          class="full bgc_fff mb_10 text_center border_radius_10"
          :class="[herf == index ? 'main_bgc color_999': '', item.isScore ? 'scored_bgi' : '']"
        > 
          <div class="w_full h_30 p_5 fs_1rem">
            <div class="w_full h_17 lh_17 ellipsis">{{ formatName(item.name).zh }}</div><br/>
            <div class="w_full h_17 lh_17 ellipsis">{{ formatName(item.name).en }}</div>
          </div>
          <div class="w_full h_full-35 relative mt_5">
            <div class="w_full pv_15">
              <span class="w_full h_55 lh_55 fs_3rem font_zh color_999">{{ str + item.personNumber }}</span> 
            </div>
            <div class="w_full h_20 lh_20 fs_1_5rem font_zh">号</div>
            <div 
              class="w_full h_30 lh_30 color_fff bgc_000000c3 border_b_radius_10 absolute left_0 bottom_0" 
              v-if="item.isScore">已评 {{ item.totalScore }} 分
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 评分 -->
    <div class="w_full h_70_p ph_0" v-show="activePerson && activePerson.id">
      <!-- 评分-图片、编号 -->
      <div class="w_full h_50_p flex_row_center p_20 mv_40">
        <div class="w_50_p h_full">
          <img class="full object_fit_cover border_radius_10" v-if="activePerson.avatar" :src="formatUserImg(activePerson.avatar)" alt="">
          <img class="full object_fit_cover border_radius_10" v-else src="../assets/image/user.png" alt="">
        </div>

        <div class="w_full-200 h_full flex_column_center pl_10 text_center">
          <div 
            class="w_full color_fff font_zh ls_3" 
            :class="screenWidth < 600 ? 'fs_1rem' : 'fs_2rem'">{{ formatName(activePerson.name).zh }}
          </div>
          <div 
            class="w_full color_fff font_zh ls_3" 
            :class="screenWidth < 600 ? 'fs_1rem' : 'fs_2rem'">{{ formatName(activePerson.name).en }}
          </div>

          <div class="text_center mt_10"> 
            <span 
              class="font_zh main_text"
              :class="screenWidth < 600 ? 'fs_3rem' : 'fs_5rem'"
            >
              {{ str + activePerson.personNumber }}
            </span> 
            <span class="fs_1_5rem color_fff font_zh">号</span> 
          </div> 
        </div>
      </div>

      <!-- 评分-表单 -->
      <div class="m_0_auto ph_20 score_form" :class="screenWidth < 600 ? 'w_full' : 'w_50_p'">
        <van-form v-if="activePerson.isScore">
          <van-field 
            disabled
            v-model="activePerson.totalScore" 
            type="number"
            label="分数" 
          />

          <div class="mv_30">
            <van-button round block  disabled color="#888" size="large">已评分</van-button>
          </div>
        </van-form>

        <van-form v-else>
          <van-field 
            v-model="scoreValue" 
            type="number"
            label="分数" 
            placeholder="请输入分数" 
          />

          <div class="mv_30">
            <van-button
              round block type="info" size="large" native-type="submit"
              color="linear-gradient(to bottom, #f7e0cf, #fa964e)" @click="clickSubmit()">提交评分
            </van-button>
          </div>
        </van-form>
      </div>
    </div>
    
    <!-- 确认提交表单 ？ -->
    <van-dialog v-model="isShowDialog" title="确认提交评分？" show-cancel-button @confirm="submitScoreForm">
      <div class="w_full ph_10 mv_20 fs_1rem">
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">分数：</div>
          <div class="w_50_p pl_5 pt_3">{{ scoreValue }}</div>
        </div>
      </div>
    </van-dialog> 


    <!-- <van-dialog v-model="isShowRuleDialog" :title="contestName + '比赛评分标准'" show-cancel-button @confirm="isShowRuleDialog=false">
      <div class="w_full h_80_p scrool_box overflow_y_auto p_20 fs_1rem"> 
        <p v-html="rule"></p>
      </div>
    </van-dialog> 

    <div 
      class="w_100 h_30 lh_30 text_center fs_1rem bgc_0000003a border_radius_5 absolute bottom_10 right_10 main_color"
      @click="showRule()">评分标准
    </div>  -->
   
  </div>
</template>

<script>
  import Tabbar from '@/components/tabbar.vue';
  import {
    getPersonTypeList,
    getPersonList,
    savePersonScore
  } from '@/api/index.js'

  import { Toast, Dialog } from 'vant';

  export default {
    name: 'PersonScore',
    components: { Tabbar },
    data() {
      return {
        screenWidth: 0,
        str: null,
        personItemWidth: 0,

        activePerson: {},

        groupList: [],
        groupId: 1001,
        personList: [],

        isShowDialog: false,

        scoreValue: null,
        herf: 0,
        
        contestId: null,
        contestName: '',
      
        rule: ''
      }
    },
    computed: {
      
    },
    async mounted() {
      let window_width = document.body.clientWidth
      this.screenWidth = window_width
      if (window_width < 600) {
        this.personItemWidth = (window_width - 10) / 3
      } else {
        this.personItemWidth = (window_width - 10) / 5
      }

      let contestId = this.$route.params.contestId
      let contestName = this.$route.params.contestName
      
      this.contestId = contestId
      this.contestName = contestName

      this.formatABC(contestId)

      document.title = contestName + '比赛评分'

      // 获取分组列表
      this.getPersonTypeList()

    },

    destroyed() {
      clearInterval(this.timer)
      this.timer = null
    },

    methods: {
      // 获取 分组列表
      async getPersonTypeList() {
        let res = await getPersonTypeList()
        try {
          if (res.code == 1000) {
            this.groupList = res.data
            this.groupId = res.data[0].id

            this.getPersonList(this.contestId, res.data[0].id)
          }
        } catch(err) {
          console.log('获取分组列表失败 : ', err);
        }
      },

      // 获取 选手列表
      async getPersonList(contestId, groupId) {
        let res = await getPersonList(contestId, groupId)
        try {
          if (res.code == 1000) {
            this.personList = res.data

            for (let i in res.data) {
              if (!res.data[i].isScore) {
                this.activePerson = res.data[i]

                this.herf = i

                this.$nextTick(() => {
                  this.handleScroolTo(this.herf)
                })
                break
              } else {
                // 如果 全部 评分完成， 显示 第一个
                this.herf = 0
                this.activePerson = res.data[0]

                this.handleScroolTo(this.herf)
              }
            }
          }
        } catch(err) {
          console.log('获取选手列表失败 : ', err);
        }
      },

      // 点击分组
      clickGroup(item) {
        this.groupId = item.id

        this.personList = []
        this.activePerson = {
          id: null,
          avatar: null
        }
        this.scoreValue = null

        Toast.loading({
          message: '加载中...',
          duration: 500,
          forbidClick: true,
        });

        setTimeout(() => {
          this.getPersonList(this.contestId, item.id)
        }, 500)
      },

      // 点击【提交】按钮， 显示确认框
      clickSubmit() {
        let validateResult = this.validateScoreForm()

        validateResult ? this.isShowDialog = true : Toast.fail('请检查表单！');
      },

      // 验证 分数
      validateScoreForm() {
        return this.scoreValue && this.scoreValue > 0 && this.scoreValue <= 10 ? true : false
      },

      // 点击 【确定】
      submitScoreForm() {
        let params = {
          contestId: parseInt(this.contestId),
          personId: parseInt(this.activePerson.id),
          totalScore: parseFloat(this.scoreValue)
        }

        this.savePersonScore(params)
      },

      // 提交评分
      async savePersonScore(params) {
        let res = await savePersonScore(params)
        try {
          if (res.code == 1000 && res.message == 'success') {
            Toast.success('提交成功！');
            this.scoreValue = null

            // 更新 personList
            this.getPersonList(this.contestId, this.groupId)

            // if (this.herf < this.personList.length) {
            //   this.clickPersonItem(this.herf ++)
            // }
          } 
        } catch(err) {
          console.log('选手评分提交失败 : ', err);
        }
      },

      showRule() {
        this.getGuiZe(this.contestId)

        this.isShowRuleDialog = true
      },

      // 获取 评分规则
      async getGuiZe(contestId) {
        let res = await getGuiZe(contestId)
        try {
          if (res.code == 1000 && res.message == 'success') {
            this.rule = res.data.guiZeContent
          }
        } catch(err) {
          console.log('获取评分规则失败 : ', err);
        }
      },

      prev() {
        if (this.herf > 0) {
          this.herf --

          this.activePerson = this.personList[this.herf]

          this.handleScroolTo(this.herf)
        }
      },

      next() {
        if (this.herf < this.personList.length - 1) {
          this.herf ++
        }

        this.activePerson = this.personList[this.herf]

        if (this.herf > 1) {
          this.handleScroolTo(this.herf)
        }
      },

      clickPersonItem(index) {
        let person_lenth = this.personList.length

        if (index < person_lenth && index >= 0) {
          this.activePerson = this.personList[index]

          this.herf = index

          this.handleScroolTo(this.herf)
        }
      },

      handleScroolTo(herf) {
        // debugger
        let width = null

        if (herf == 0) {
          width = 0
        } else {
          if (this.screenWidth < 600) {
            width = (herf - 1) * this.personItemWidth
          } else {
            width = (herf - 2) * this.personItemWidth
          }
        }

        this.$refs.scroll_box.scrollTo(width, 0)
      },

      formatName(name) {
        let str = name.trim().split(" ")
        let str_2 = str.pop()

        let result = {
          zh: str_2,
          en: str.join(" ") 
        }

        return result
      },

      // 格式化 图片,
      formatUserImg(str) {
        let list = str.split(',')

        return list[0]
      },

      // 
      formatABC(id) {
        if (id == 3) {
          this.str = 'A'
        } else if (id == 1) {
          this.str = 'B'
        } else if (id == 2) {
          this.str = 'C'
        } else {
          this.str = ''
        }
      }
    }
  }
</script>

<style>
  .score_form > .van-form > .van-cell::after { left: 0; right: 0; }
  .score_form > .van-form > .van-cell { border-radius: 10px; }

  .van-cell__title > span { font-size: 1rem !important; }
  .van-cell { padding: 15px 10px; }
  .van-field__body > input { font-size: 1.3rem !important; }
  .van-dialog__header { font-size: 1rem !important; }
  .van-button__text { font-size: 1rem !important; color: #000 !important; }

  .list_box { scroll-behavior: smooth; }

  .text_normal { white-space: pre-line; align-content: center; }
</style>